//
//  MineSettingViewController.swift
//  MT
//
//  Created by M on 2019/12/31.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition

class MineSettingViewController: BaseViewController {
    
    @objc
    enum SettingType: Int {
        case about = 0
        case clearCache
        case contactCustomerService
        case updatePwd
        case share
        
        /// 标题
        var title: String {
            switch self {
            case .updatePwd:
                return "修改密码"
            case .about:
                return "关于觅颜"
            case .clearCache:
                return "清空缓存"
            case .contactCustomerService:
                return "联系客服"
            case .share:
                return "分享"
            }
        }
        
        /// 展示
        var detail: Any {
            switch self {
            case .updatePwd:
                return ""
            case .about:
                let infoDict = Bundle.main.infoDictionary!
                let minorVersion = infoDict["CFBundleShortVersionString"]//版本号（内部标示）
                return minorVersion as! String
            case .clearCache:
                return MTCache.returnCacheSize() + " MB"
            case .contactCustomerService:
                return ""
                return UIImage(named: "WeChat") as Any
            case .share:
                return "更多乐趣尽在分享"
            }
        }
        
        /// 是否展示 > 图标
        var isIndicatorNeeded: Bool {
            switch self {
            case .contactCustomerService, .updatePwd:
                return true
            default:
                return false
            }
        }
    }
    
    /// 展示顺序
    var displayType: [SettingType] = [.updatePwd,.contactCustomerService,.about, .clearCache, ]
    var displayTypeRelease: [SettingType] = [.about, .clearCache, .contactCustomerService, .share]
    
    lazy var tableView: UITableView = {
        let tv = UITableView(frame: self.view.bounds, style: .grouped)
        tv.delegate = self
        tv.dataSource = self
        tv.showsVerticalScrollIndicator = false
        tv.backgroundColor = UIColor(hex: 0xf6f6f6)
        tv.register(MineSettingTableViewCell.self, forCellReuseIdentifier: String(describing: MineSettingTableViewCell.self))
        return tv
    }()
    
    /// Logout
    lazy var logoutButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("退出登录", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(settingViewController(didClickLogoutButton:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var wxPublicAccLab : UILabel = {
        let label = UILabel()
        label.text = "关注我们获得更多福利"
        label.font = PingFangSCMediumFont(12)
        label.textColor = UIColor(hex:0x9b9b9b)
        label.textAlignment = .center
        return label
    }()
    
    lazy var wxIcon : UIImageView = {
        let wxImage = UIImageView()
        wxImage.image = UIImage(named: "WeChat")
        wxImage.contentMode = .scaleAspectFill
        wxImage.clipsToBounds = true
        wxImage.layer.cornerRadius = 25
        wxImage.isUserInteractionEnabled = true
        let wxTap = UITapGestureRecognizer(target: self, action: #selector(settingViewController(didClickWXButton:)))
        wxImage.addGestureRecognizer(wxTap)
        return wxImage
    }()
    
    lazy var wxPublicAccStr : UILabel = {
        let label = UILabel()
        label.text = "公众号"
        label.font = PingFangSCMediumFont(12)
        label.textColor = UIColor(hex:0x1d1a1a)
        label.textAlignment = .center
        label.layer.borderColor = UIColor(hex:0x9b9b9b).cgColor
        label.layer.borderWidth = 0.5
        label.layer.cornerRadius = 10
        return label
    }()
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MineSettingViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MineSettingViewController {
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "设置"
        view.addSubview(tableView)
        view.addSubview(logoutButton)
        view.addSubview(wxPublicAccLab)
        view.addSubview(wxIcon)
        view.addSubview(wxPublicAccStr)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        logoutButton.snp.makeConstraints { (make) in
            make.right.equalTo(view).offset(-20)
            make.left.equalTo(view).offset(20)
            make.height.equalTo(50)
            make.centerY.equalTo(view).offset(40)
        }
        wxPublicAccLab.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 124)
        }
        
        wxIcon.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.width.height.equalTo(50)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 64)
        }
        
        wxPublicAccStr.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.width.equalTo(60)
            make.height.equalTo(20)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 40)
        }
    }
    
}


// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MineSettingViewController {
    
    private func settingViewController(didClickLogoutButton sender: UIButton) {
        UserCenter.default.logout()
    }
    
    private func settingViewController(didClickWXButton sender: UIButton) {
        
    }
    
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ UITableViewDelegate ----------------------------------------
extension MineSettingViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var t: SettingType = .share
        if UserDefaults.AppValidate.isValidate.storedBool {
            t = self.displayTypeRelease[indexPath.row]
        } else {
            t = self.displayType[indexPath.row]
        }
        switch t {
        case .updatePwd:
            let vc = MTInputPhoneController()
            vc.titleStr = "请输入绑定的手机号"
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case .about:
//            let c = MTAboutMeViewController()
//            self.navigationController?.pushViewController(c, animated: true)
            break
            
        case .clearCache:
            let c = UIAlertController(title: "清空缓存", message: nil, preferredStyle: .alert)
            let a1 = UIAlertAction(title: "确定", style: .default) { (_) in
                MTCache.cleanCache {
                    AlertManager.presentAlertView(message: "清理成功")
                    tableView.reloadRows(at: [indexPath], with: .none)
                }
            }
            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            c.addAction(a1)
            c.addAction(cancel)
            self.present(c, animated: true, completion: nil)
            break
            
        case .contactCustomerService:
//            let c = UIAlertController(title: "复制微信公众号", message: "关注微信公众号【觅颜团队】\n即可在线帮您提现和解答问题", preferredStyle: .alert)
//            let a1 = UIAlertAction(title: "复制", style: .default) { (_) in
//                UIPasteboard.general.string = "觅颜团队"
//                AlertManager.presentAlertView(message: "复制成功")
//            }
//            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//            c.addAction(a1)
//            c.addAction(cancel)
//            self.present(c, animated: true, completion: nil)
            if let un = UserCenter.default.customerUserName {
                JMSGConversation.createSingleConversation(withUsername: un) { [weak self] (conversation, error) in
                    guard let weakSelf = self else { return }
                    if error == nil, conversation != nil {
                        if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                            nav.selectCategory()
                            
                            DispatchQueue.main.after(0.25) {
                                let conv: JMSGConversation = conversation as! JMSGConversation
                                nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                            }
                            
                            DispatchQueue.main.after(1, execute: {
                                weakSelf.navigationController?.popToRootViewController(animated: false)
                            })
                        }
                    }
                }
            }
            break
        
        case .share:
            if WXApi.isWXAppInstalled() {
                let shareModle: ShareModel = ShareModel()
                shareModle.title = "觅颜APP"
                shareModle.desc = "觅颜APP,发现更多美"
                shareModle.imageUrl = "Icon-60"
                shareModle.webUrl = shareUrl
                MTShareManager.share(platformtype: .wechatType, sharemodel: shareModle, shareType: .shareWeb)
            } else {
                AlertManager.presentAlertView(message: "分享需要安装微信")
            }
        }
    }
    
}

// MARK: ------------------------------------ UITableViewDataSource ----------------------------------------
extension MineSettingViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return UserDefaults.AppValidate.isValidate.storedBool ? displayTypeRelease.count : displayType.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MineSettingTableViewCell.self), for: indexPath) as? MineSettingTableViewCell else {
            return tableView.dequeueReusableCell(withIdentifier: String(describing: MineSettingTableViewCell.self), for: indexPath)
        }
        if UserDefaults.AppValidate.isValidate.storedBool {
            cell.settingType = self.displayTypeRelease[indexPath.row]
        } else {
            cell.settingType = self.displayType[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
